//
//  APPRootViewController.swift
//  tree_ai
//
//  Created by oldmacbook on 2024/5/25.
//

import UIKit
import ZLPhotoBrowser
import Alamofire
import ProgressHUD

class PlantTableViewCell: UITableViewCell {
    let plantImageView = UIImageView()
    let nameLabel = UILabel()
    let descriptionLabel = UILabel()
    let updateTimeLabel = UILabel()

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        // 添加子视图
        addSubview(plantImageView)
        addSubview(nameLabel)
        addSubview(descriptionLabel)
        addSubview(updateTimeLabel)
        
        // 设置字体和颜色
        nameLabel.font = UIFont.systemFont(ofSize: 14)
        descriptionLabel.font = UIFont.systemFont(ofSize: 11)
        updateTimeLabel.font = UIFont.systemFont(ofSize: 9)
        
        nameLabel.textColor = .darkText
        descriptionLabel.textColor = .gray
        descriptionLabel.numberOfLines = 3
        updateTimeLabel.textColor = .lightGray
    
        
//        plantImageView.translatesAutoresizingMaskIntoConstraints = false
//        nameLabel.translatesAutoresizingMaskIntoConstraints = false
//        descriptionLabel.translatesAutoresizingMaskIntoConstraints = false
//        updateTimeLabel.translatesAutoresizingMaskIntoConstraints = false
        // 设置自动布局
        plantImageView.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(10)
            //make.top.equalToSuperview().offset(10)
            make.centerY.equalToSuperview()
            //make.bottom.equalToSuperview().offset(-10)
            make.width.height.equalTo(80) // 宽度和高度相同
        }
        
        nameLabel.snp.makeConstraints { make in
            make.leading.equalTo(plantImageView.snp.trailing).offset(10)
            make.top.equalToSuperview().offset(10)
        }
        
        descriptionLabel.snp.makeConstraints { make in
            make.leading.equalTo(nameLabel.snp.leading)
            make.top.equalTo(nameLabel.snp.bottom).offset(5)
            make.trailing.equalToSuperview().offset(-10) // 右边界与cell保持10点距离
            make.bottom.equalTo(updateTimeLabel.snp.top).offset(-5)
        }
        
        updateTimeLabel.snp.makeConstraints { make in
            make.leading.equalTo(nameLabel.snp.leading)
            make.top.equalTo(descriptionLabel.snp.bottom).offset(5)
            make.bottom.equalToSuperview().offset(-10)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}






class RecordListViewController: UIViewController,UITableViewDelegate, UITableViewDataSource {

    var allTrees: [Tree]?
    
    let tableView = UITableView()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.createView()
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        self.reloadFromDataBase()
        
    }

    func reloadFromDataBase() {
        self.allTrees = TreeSqlManager.shared.getAllTrees()
        self.tableView.reloadData()
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    func createView() {
//        self.view.backgroundColor = .gray
//        let testBtn = UIButton()
//        self.view.addSubview(testBtn)
//        testBtn.setTitle("测试", for: .normal)
//        testBtn.setTitleColor(.blue, for: .normal)
//        testBtn.snp.makeConstraints { make in
//            make.top.equalTo(120)
//            make.left.equalTo(30)
//            make.width.equalTo(100)
//            make.height.equalTo(40)
//        }
//        testBtn.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
//             
//        
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(PlantTableViewCell.self, forCellReuseIdentifier: "PlantCell")
        view.addSubview(tableView)
        
        // 设置TableView的布局约束
        tableView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            tableView.topAnchor.constraint(equalTo: view.topAnchor),
            tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
        ])
        
    }
    
    // UITableViewDataSource methods
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.allTrees!.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "PlantCell", for: indexPath) as! PlantTableViewCell
        
        // 根据indexPath获取对应的数据
        let plant = self.allTrees![indexPath.row]
        var treeName = plant.name
        var treeDesc = plant.desc.replacingOccurrences(of: "\n", with: " ")
        
        if treeName=="" {
            treeName = "未识别"
        }
        if treeDesc=="" {
            treeDesc = "未识别 \n\n\n"
        }
        
        // 配置cell
        //ell.plantImageView.image = UIImage(named: plant.imageName)
        cell.plantImageView.af.setImage(withURL: URL(string: plant.image_url)!)
        cell.nameLabel.text = treeName
        cell.descriptionLabel.text = treeDesc
        cell.updateTimeLabel.text = timestampToInt64Date(timestamp: plant.update_time)
        
        return cell
    }
    
    func timestampToInt64Date(timestamp: Int64) -> String {
        let date = Date(timeIntervalSince1970: TimeInterval(timestamp))
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" // 根据需要设置日期格式
        dateFormatter.timeZone = TimeZone.current // 设置时区，这里使用当前时区
        return dateFormatter.string(from: date)
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        // 处理单元格点击事件
        //print("Clicked on row: \(indexPath.row)")
        
        // 如果你想在点击后取消选中状态
        tableView.deselectRow(at: indexPath, animated: true)
        
        let plant = self.allTrees![indexPath.row]
        
        
        let findInfoVc = FindInfoViewController.init()
        findInfoVc.localTreeId = plant.id
        self.navigationController?.pushViewController(findInfoVc, animated: true)
    }
    
//
//<<<<<<< HEAD:tree_ai/tree_ai/APPRootViewController.swift
//    @objc func buttonTapped() {
//        // 这里是按钮点击后的处理逻辑
//        print("Button was tapped")
//        //let findInfoVc = FindInfoViewController.init()
//        //self.navigationController?.pushViewController(findInfoVc, animated: true)
//        
//        let config = ZLPhotoConfiguration.default()
//        config.maxSelectCount = 1
//        config.allowEditImage = false
//        config.allowSelectVideo = false
//        config.allowSelectOriginal = false
//        config.allowTakePhotoInLibrary = true
//    
//        
//        let ps = ZLPhotoPreviewSheet()
//        
//        ps.selectImageBlock = { [weak self] results, isOriginal in
//            // your code
//            print("select: \(results)  isOriginal:\(isOriginal)")
//            if (results.count > 0) {
//                let imgModel = results[0]
//                
//                self?.uploadImage(img: imgModel.image)
//            }
//        }
//        //ps.showPhotoLibrary(sender: self)
//        
//        ps.showPreview(sender: self)
//        
//    }
//    
//    func uploadImage(img: UIImage) {
//        //ProgressHUD.progress(0)
//        ProgressHUD.showProgress(0)
//        let imgSize = img.size
//        print("imgSize: \(imgSize)")
//        
//        let uuid = TreeSqlManager.shared.snowFlake.nextID()
//        let fileName = String(format: "%llu.jpg", uuid!)
//        
//        let imgData = img.jpegData(compressionQuality: 0.85)
//        
//        let uploadURL = "https://chatglm.cn/chatglm/backend-api/assistant/file_upload"
//        
//        var request = URLRequest(url: URL(string: uploadURL)!)
//        request.httpMethod = "POST"
//        
//        
//        AF.upload(multipartFormData: { multipartFormData in
//            multipartFormData.append(imgData!, withName: "file", fileName: fileName) //, mimeType: "jpg"
//        }, with: request).uploadProgress(closure: { progress in
//            print("progress:\(progress)")
//            //ProgressHUD.progress(progress.fractionCompleted)
//            ProgressHUD.showProgress(progress.fractionCompleted)
//        })
//        .responseJSON { response in
//            switch response.result {
//                case .success:
//                    print("Upload finish")
//                    if let json = response.value {
//                        print("JSON type:\(type(of:json)): \(json)")
//                        let jsonDict = json as? Dictionary<String, Any>
//                        let resultDict = jsonDict?["result"] as? Dictionary<String, Any>
//                        if resultDict != nil {
//                            let file_id = resultDict?["file_id"] as? String
//                            let file_name = resultDict?["file_name"] as? String
//                            let file_url = resultDict?["file_url"] as? String
//                            let file_size = resultDict?["file_size"] as! Int64
//                            
//                            let rowId = TreeSqlManager.shared.insertTree(image_name: file_name!, image_url: file_url!, image_id: file_id!, image_file_size: file_size)
//                            self.reloadFromDataBase()
//                            
//                            let findInfoVc = FindInfoViewController.init()
//                            findInfoVc.localTreeId = rowId
//                            self.navigationController?.pushViewController(findInfoVc, animated: true)
//                            
//                        }
//                        
//                    }
//                    //ProgressHUD.succeed("上传成功！")
//                    ProgressHUD.showSucceed("上传成功！", interaction: false, delay: 1.0)
//                
//                case .failure(let error):
//                    print("Upload failed: \(error.localizedDescription)")
//            }
//        }
//    }
//    
//=======
//>>>>>>> 698d309 (no message):tree_ai/tree_ai/RecordListViewController.swift
    
}
